<template>
  <view class="health-history-page">
    <!-- 日期选择器（仅显示年月日） -->
    <view class="date-picker-container">
		<text>请选择日期</text>
      <wd-datetime-picker 
        v-model="tempSelectedDate" 
        :formatter="dateFormatter" 
        :min-date="ninetyDaysAgo"
        :max-date="today"
        type="date"
        @confirm="handleConfirm" 
      />
    </view>

    <!-- 选中日期提示 -->
    <view class="selected-date-tip" v-if="isDateSelected">
      已选择：{{ formatShowDate(selectedDate) }}
    </view>

    <!-- 健康数据列表容器 -->
    <view class="health-data-container">
      <!-- 未选择日期提示 -->
      <view class="empty-data" v-if="!isDateSelected">
        <wd-icon name="calendar" size="60rpx" color="#ccc"></wd-icon>
        <view class="empty-text">请选择日期并点击完成按钮</view>
      </view>

      <!-- 空数据状态（已选择日期但无数据） -->
      <view class="empty-data" v-if="isDateSelected && currentDayData.length === 0">
        <wd-icon name="data-line" size="60rpx" color="#ccc"></wd-icon>
        <view class="empty-text">该日期暂无健康数据记录</view>
      </view>

      <!-- 健康数据列表（handleConfirm执行后显示） -->
      <view class="data-item" v-for="(item, idx) in currentDayData" :key="idx" v-if="isDateSelected">
        <view class="item-icon" :class="item.iconType">
          <wd-icon :name="item.icon" size="42rpx"></wd-icon>
        </view>
        <view class="item-info">
          <view class="info-name">{{ item.type }}</view>
          <view class="info-time">测量时间：{{ item.measureTime }}</view>
        </view>
        <view class="item-value">
          <view class="current-value">{{ item.value }}</view>
          <view class="normal-range">正常范围：{{ item.normalRange }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 日期选择器确认事件 - 核心修改点
function handleConfirm({ value }) {
  console.log("选择的日期:", new Date(value))
  
  // 1. 保存确认后的日期
  selectedDate.value = value
  isDateSelected.value = true
  
  // 2. 加载该日期的健康数据（仅在handleConfirm执行后才会触发）
  currentDayData.value = generateMockData(value)
}

// 日期相关状态
const today = ref(Date.now())
const ninetyDaysAgo = ref(Date.now() - 90 * 24 * 60 * 60 * 1000)
const tempSelectedDate = ref(Date.now()) // 临时存储选择的日期
const selectedDate = ref(null) // 确认后的日期
const isDateSelected = ref(false) // 是否已通过handleConfirm确认

// 数据相关状态
const currentDayData = ref([])
const healthDataType = ref('')

// 日期格式化
const dateFormatter = (type, value) => {
  switch (type) {
    case 'year': return `${value}年`
    case 'month': return `${value}月`
    case 'date': return `${value}日`
    default: return value
  }
}

// 生成Mock数据
const generateMockData = (targetDate) => {
  const dataTemplates = [
    {
      type: '血压',
      icon: 'heart',
      iconType: 'icon-bp',
      normalRange: '90-140/60-90 mmHg',
      generateValue: () => `${Math.floor(Math.random() * 30 + 120)}/${Math.floor(Math.random() * 20 + 70)} mmHg`
    },
    {
      type: '血糖',
      icon: 'droplet',
      iconType: 'icon-glucose',
      normalRange: '3.9-6.1 mmol/L',
      generateValue: () => (Math.random() * 2 + 4).toFixed(1) + ' mmol/L'
    },
    {
      type: '心率',
      icon: 'pulse',
      iconType: 'icon-heartrate',
      normalRange: '60-100 次/分',
      generateValue: () => `${Math.floor(Math.random() * 30 + 60)} 次/分`
    }
  ]

  const targetTemplates = healthDataType.value 
    ? dataTemplates.filter(tpl => tpl.type === healthDataType.value) 
    : dataTemplates

  const dataCount = Math.floor(Math.random() * 3) + 1
  const mockList = []
  for (let i = 0; i < dataCount; i++) {
    const randomTpl = targetTemplates[Math.floor(Math.random() * targetTemplates.length)]
    const hour = Math.floor(Math.random() * 12) + 8
    const minute = Math.floor(Math.random() * 60)
    const measureTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
    
    mockList.push({
      ...randomTpl,
      value: randomTpl.generateValue(),
      measureTime: measureTime,
      date: targetDate
    })
  }
  return mockList
}

// 格式化显示日期
const formatShowDate = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

// 返回上一页
const handleGoBack = () => {
  uni.navigateBack({ delta: 1 })
}

// 页面加载
onLoad((options) => {
  healthDataType.value = options.type ? decodeURIComponent(options.type) : ''
})
</script>

<style lang="less" scoped>
/* 样式保持不变 */
.health-history-page {
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 96rpx;
  background-color: #fff;
  padding: 0 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 99;

  .header-left {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #333;
  }

  .header-title {
    font-size: 34rpx;
    font-weight: 600;
    color: #333;
  }

  .header-right {
    width: 40rpx;
  }
}

.date-picker-container {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.confirm-btn {
  width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  background-color: #1677ff;
  color: #fff;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  margin-left: 20rpx;
}

.selected-date-tip {
  padding: 16rpx 30rpx;
  background-color: #fff;
  font-size: 26rpx;
  color: #666;
  border-bottom: 1rpx solid #f0f0f0;
}

.health-data-container {
  padding: 20rpx;
}

.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
  color: #999;

  .empty-text {
    margin-top: 20rpx;
    font-size: 28rpx;
  }
}

.data-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin-bottom: 16rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
}

.item-icon {
  width: 90rpx;
  height: 90rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;

  &.icon-bp {
    background-color: #e6f4ff;
    color: #1890ff;
  }

  &.icon-glucose {
    background-color: #fff2e8;
    color: #fa8c16;
  }

  &.icon-heartrate {
    background-color: #ffe6e6;
    color: #f5222d;
  }
}

.item-info {
  flex: 1;

  .info-name {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 6rpx;
  }

  .info-time {
    font-size: 22rpx;
    color: #999;
  }
}

.item-value {
  text-align: right;
  min-width: 220rpx;

  .current-value {
    font-size: 26rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 6rpx;
  }

  .normal-range {
    font-size: 22rpx;
    color: #666;
  }
}
</style>
    